<template>
  <el-card class="box-card">
    <div id="main" style="width: 100%;height:650px"></div>
  </el-card>
</template>
  
<script setup>
import * as echarts from 'echarts';
import {inject, onMounted, onUnmounted, watch} from "vue";
import { getData } from "@/api/common";
import { useRoute } from "vue-router";
import { store } from "@/store";

const route = useRoute();

console.log(route.query);

const myEcharts = echarts;
// 调用 App.vue 提供的方法，进行刷新
const reload = inject("reload")

watch(route, (newValue) => {
  console.log(newValue);
  myEcharts.dispose;
  // reload() // 刷新页面
  initChart();
});

onMounted(() => {
  initChart();
});
onUnmounted(() => {
  myEcharts.dispose;
});

const initChart = async () => {
  // 获取缓存中的数据
  let data = store.state.dataObj[route.query.id];
  // 不存在数据
  if (!data) {
    data = await getData(route.query.id);
    // 存储数据
    store.commit("setData", { 'name': route.query.id, 'data': data});
  }
  
  // 基于准备好的dom，初始化echarts实例
  const myChart = myEcharts.init(document.getElementById('main'), "purple-passion");
  const option = {
    title: {
      left: 'center',
      text: `${route.query.name}辐射水平`
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      type: 'scroll',
      top: 30,
      data: data.legend
    },
    grid: {
      left: '3%',
      right: '5%',
      top: '15%',
      bottom: '8%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      name: '时间',
      boundaryGap: false,
      data: data.xAxis,
    },
    yAxis: {
      type: 'value',
      name: '数值',
      min: 0,
    },
    series: data.series,
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  }
  // 如果数据大于20条添加区域缩放 dataZoom
  if (data.xAxis.length > 20) {
    option['dataZoom'] = [
      {
        type: 'inside',
        start: 0,
        end: 20
      },
      {
        start: 0,
        end: 20
      }
    ]
  }
  // 绘制图表
  myChart.setOption(option);

  window.onresize = function () {
    myChart.resize();
  };
}
</script>
  
<style lang="scss" scoped>
</style>